var sounddb = require('../../db/sound.db')
var musicdb = require('../../db/music.db')
var orderdb = require('../../db/order.db')
var config = require('../../config')
var logger = require('../../logger')
var emit = require('../../emit')
var async = require('async')

function onsocket(socket, data) {
    var infoList = [];
    async.waterfall([
        function (callback) {
            orderdb.getallorders(socket.handshake.cookies.authorized, (err, response) => {
                callback(err, response);
            });
        },
        function (response, callback) {
            async.forEach(response, (r, cb) => {
                var ids = JSON.parse(r).ids;
                var infos = new Array();
                async.forEach(ids, (id, cb2) => {
                    sounddb.getfileinfo(id, function (err, info) {
                        if (info != null) {
                            infos.push(info);
                        }
                        cb2(null);
                    });
                }, (err) => {
                    if (err) {
                        cb(err);
                    } else {
                        infoList.push(infos);
                        cb(null);
                    }
                });
            }, (err) => {
                if (err) {
                    callback(err);
                }
                else {
                    callback(null, response);
                }
            })
        }
    ], (err, response) => {
        if (err) {
            logger.log(err);
        } else {
            var data = { results: response, infos: infoList };
            if (config.debug) {
                logger.log(data);
            } else {
                emit.send(socket, 'getorderlist', data);
            }
        }
    });
}


module.exports = {
    onsocket
}